from _datetime import datetime
import json
from django import http
from django.views import View
from django.http import JsonResponse

from aijia_house.utils.views import LoginRequiredJSONMixin
from apps.house.models import House
from apps.order.models import Order
from django.views import View

from apps.users.models import User
from .models import Order


# class UpdateOrderView(LoginRequiredJSONMixin, View):
class UpdateOrderView(View):
    # 添加订单
    def post(self, request):
        # 1.接收参数
        data_dict = json.loads(request.body.decode())
        house_id = data_dict.get('house_id')
        begin_date = data_dict.get('begin_date')  # 字符串
        end_date = data_dict.get('end_date')
        # 2 校验参数

        if not all([house_id, begin_date, end_date]):
            return JsonResponse({'errno': 4105, 'errmsg': '参数不足'})
        # 3 日期和天数
        try:
            begin_date = datetime.strptime(begin_date, '%Y-%m-%d')
            end_date = datetime.strptime(end_date, '%Y-%m-%d')
            # begin_date = int(begin_date)
            # end_date = int(end_date)
            if end_date > begin_date:
                days = (end_date - begin_date).days
                # days = end_date - begin_date
        except Exception as e:
            return JsonResponse({'errno': 4103, 'errmsg': '参数错误'})

        # 4 判断房屋是否存在
        try:
            house = House.objects.get(pk=house_id)
        except Exception as e:
            return JsonResponse({'errno': 4002, 'errmsg': '库中无数据'})

        # # 5 判断是否是房东
        # 接收应是变量,目前是常量
        user = User.objects.get(id=2)
        # user = request.user
        # if house.user_id == user.id:
        #     return JsonResponse({'errno': 4105, 'errmsg': '本房屋房东不可预定'})

        # 6 判断房屋是否被人预定
        count = Order.objects.filter(house_id=house_id,
                                     begin_date__lt=end_date,
                                     end_date__gt=begin_date).count()
        if count > 0:
            return JsonResponse({'errno': 4003, 'errmsg': '房屋已被别人预定'})

        # 7 保存到数据库
        try:
            order = Order.objects.create(
                user=user,
                house=house,
                begin_date=begin_date.strftime("%Y-%m-%d"),
                # begin_date=begin_date,
                end_date=end_date.strftime("%Y-%m-%d"),
                # end_date = end_date,
                days=days,
                house_price=house.price,
                amount=days * house.price,
            )
        except Exception as e:
            print(e)
            return JsonResponse({'errno': 4004, 'errmsg': '订单未添加成功'})

        return JsonResponse({'errno': 0,
                             'errmsg': '订单添加成功',
                             'data': {"order_id": order.id}})

    # 展示订单
    def get(self, request):
        # user = request.user
        # 接收应是变量,目前是常量
        user = User.objects.get(id=4)

        # 1 获取参数
        json_data = json.loads(request.body.decode())
        role = json_data.get('role')

        # 2 校验参数
        if role is None:
            return JsonResponse({'errno': 4004, 'errmsg': '参数错误'})
        if role not in ("custom", "landlord"):
            return JsonResponse({'errno': 4004, 'errmsg': "参数错误"})

        # 3 取出订单（判断是房东还是房客）
        try:
            if role == 'custom':  # 房客
                orders = Order.objects.filter(user=user).order_by('-create_time')
            elif role == 'landlord':  # 房东
                # 房东查询自己所要租的所有房子
                houses = House.objects.filter(user=user)
                house_ids = [house.id for house in houses]
                # 房东查询自己已经租出去的房子
                orders = Order.objects.filter(house_id__in=house_ids).order_by('-create_time')
        except Exception as e:
            return JsonResponse({'errno': 4004, 'errmsg': '参数错误'})

        # 4 将订单信息添加到列表中
        order_list = []
        for order in orders:
            order_list.append({
                'amount': order.amount,
                'comment': order.comment,
                'ctime': order.create_time.strftime("%Y-%m-%d %H:%M:%S"),
                'days': order.days,
                'end_date': order.end_date.strftime('%Y-%m-%d'),
                'img_url': order.house.index_image_url,
                'order_id': order.id,
                'start_date': order.begin_date.strftime('%Y-%m-%d'),
                'status': order.status,
                'title': order.house.title
            })

        # 5 响应成功
        return JsonResponse({'errno': 0,
                             'errmsg': '订单展示成功',
                             'data': {"orders": order_list}})

    # 接单/拒单
    def put(self, request):
        # user = request.user
        # 接收应是变量,目前是常量
        user = User.objects.get(id=4)

        # 1 接收参数（订单号和操作）
        data_dict = json.loads(request.body.decode())
        order_id = data_dict.get('order.id')
        action = data_dict.get('action')

        # 2 校验参数
        if not all([order_id, action]):
            return JsonResponse({'errno': 4001, 'errmsg': '参数不足'})

        if action not in ('accept', 'reject'):
            return JsonResponse({'errno': 4001, 'errmsg': '参数不足'})

        # 查询订单处于等待状态
        try:
            order = Order.objects.filter(pk=order_id, status='WAIT_ACCEPT')
        except Exception as e:
            return JsonResponse({'errno': 4004, 'errmsg': '数据错误'})

        # 查询当前订单的房东是否是当前登录用户
        # if user != order.house.user:
        #     return JsonResponse({'errno': 4105, 'errmsg': '用户身份错误'})

        # 4 更改订单状态
        try:
            if action == 'accept':
                # order.status = 'WAIT_COMMENT'
                Order.objects.filter(pk=order_id).update(status='WAIT_COMMENT')
            elif action == 'reject':
                order.status = 'REJECTED'
                comment = data_dict.get('comment')
                if not comment:
                    return JsonResponse({'errno': 4103, 'errmsg': '请输入拒绝原因'})
                order.comment = comment
                Order.objects.filter(pk=order_id).update(comment=comment)
        except Exception as e:
            print(e)
            return JsonResponse({'errno': 4001, 'errmsg': '保存错误'})

        return JsonResponse({'errno': 0, 'errmsg': '接收成功'})


#  订单评价
# class OrderEvaluation(LoginRequiredJSONMixin, View):
class OrderEvaluation(View):
    """订单评价"""

    def put(self, request):
        # 获取用户登录
        # user = request.user
        # 接收应是变量,目前是常量
        user = User.objects.get(id=2)

        # 获取参数
        json_dict = json.loads(request.body.decode())
        comment = json_dict.get("comment")
        order_id = json_dict.get("order_id")

        # 判断参数
        if not all([comment, order_id]):
            return http.JsonResponse({"errno": 4103, "errmsg": "参数错误"})

        # 进行判断，用户评论是否符合要求
        try:
            order = Order.objects.filter(pk=order_id, status="WAIT_COMMENT")

        except Exception as e:
            print(e)
            return http.JsonResponse({"errno": 4001, "errmsg": "数据库查询失败"})

        # 保存评论
        try:
            # 修改订单状态为"已完成"
            order.status = "COMPLETE"
            # 添加评论内容
            order.comment = comment
            # 提交
            # Order.save(comment)
            Order.objects.filter(pk=order_id).update(comment=comment)
        except Exception as e:
            return http.JsonResponse({"errno": 4004, "errmsg": "数据库保存失败"})

        return http.JsonResponse({"errno": 0, "errmsg": "OK"})
